/*
 * Copyright 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.wizardpager.wizard.ui;

import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.example.android.wizardpager.wizard.model.DatePage;
import com.example.android.wizardpager.wizard.model.Page;
import com.example.goodog.R;
import com.example.goodog.Utils;

public class DateFragment extends Fragment {
	private static final String ARG_KEY = "key";
	private static final int MAX_AGE_IN_MONTHES = 30*12;
	private static final int START_AGE_IN_MONTHES = 3*12;
	
	

    private PageFragmentCallbacks mCallbacks;
    private String mKey;
    private Page mPage;
    private String label;
    
    private TextView tvDate;
    private TextView tvAge;
    private SeekBar seekBar;
    private Calendar calendar;
    private Button inc;
    private Button dec;
    private LinearLayout seekBarLL;

    public static DateFragment create(String key) {
        Bundle args = new Bundle();
        args.putString(ARG_KEY, key);

        DateFragment fragment = new DateFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public DateFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle args = getArguments();
        mKey = args.getString(ARG_KEY);
        mPage = mCallbacks.onGetPage(mKey);

        DatePage DatePage = (DatePage) mPage;
        label = DatePage.getLabel();
        
        calendar = Calendar.getInstance();
        Date now = new Date();
		calendar.setTime(now);
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_page_empty, container, false);
        ((TextView) rootView.findViewById(android.R.id.title)).setText(mPage.getTitle());

        final LinearLayout ll = (LinearLayout) rootView.findViewById(R.id.mainLL);        
        
        tvDate = new TextView(getActivity());
        tvAge = new TextView(getActivity());
        tvDate.setPadding(0, 10, 0, 10);
        tvAge.setPadding(0, 10, 0, 10);
        
        seekBarLL = new LinearLayout(getActivity());
        seekBarLL.setOrientation(LinearLayout.HORIZONTAL);
        seekBarLL.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        
        inc = new Button(getActivity());
        inc.setText(">");
        inc.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        inc.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				seekBar.incrementProgressBy(1);
				
			}
		});
        inc.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				
				Thread thread = new Thread()
				{
				    @Override
				    public void run() {
				        try {
				            while(inc.isPressed()) {
				            	seekBar.incrementProgressBy(1);
				                sleep(150);
				            }
				        } catch (InterruptedException e) {
				            e.printStackTrace();
				        }
				    }
				};
				thread.start();
				
				return true;
			}
		});
        
        
        dec = new Button(getActivity());
        dec.setText("<");
        dec.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        dec.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				seekBar.incrementProgressBy(-1);
				
			}
		});
        dec.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				
				Thread thread = new Thread()
				{
				    @Override
				    public void run() {
				        try {
				            while(dec.isPressed()) {
				            	seekBar.incrementProgressBy(-1);
				                sleep(150);
				            }
				        } catch (InterruptedException e) {
				            e.printStackTrace();
				        }
				    }
				};
				thread.start();
				
				return true;
			}
		});
        
        seekBar = new SeekBar(getActivity());  
        seekBar.setPadding(10, 0, 10, 0);
        seekBar.setMax(MAX_AGE_IN_MONTHES);
        seekBar.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,1f));
        seekBar.setProgress(START_AGE_IN_MONTHES);
        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
								
				Calendar cal = (Calendar) calendar.clone();
				cal.add(Calendar.MONTH, -progress);
				
				String dateMMyy = Utils.DateToString(cal.getTime(), "MM/yy");
				String dateMMMMyyyy = Utils.DateToString(cal.getTime(), "MMMM yyyy");
				tvDate.setText("Date: "+dateMMMMyyyy);
				
				tvAge.setText(String.format("Age: %d,%d",progress/12,progress%12));
				
				Log.i("gg", "progress "+progress);
				
				mPage.getData().putString(Page.TEXT_DATA_KEY, dateMMyy);
				mPage.notifyDataChanged();
				
					
			}
		});
        
        String dateString = mPage.getData().getString(Page.TEXT_DATA_KEY, "");
        if(!dateString.equals(""))
        {
        	Date date = Utils.StringToDate(dateString, "MM/yy");
        	
        	int monthDiff = Utils.monthsBetween(calendar.getTime(), date);

        	Log.i("gg", "monthDiff "+monthDiff);
        	
        	int progress = monthDiff;
        	        if(progress != -1)
        	        {
        	        	seekBar.setProgress(progress);
        	        }
        }
        
        
        
        
        TextView mNameView = ((TextView) rootView.findViewById(R.id.label));
        mNameView.setText(label);
			
        seekBarLL.addView(dec);
        seekBarLL.addView(seekBar);
        seekBarLL.addView(inc);
        
		ll.addView(tvDate);
		ll.addView(seekBarLL);
		ll.addView(tvAge);
        
        
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if (!(activity instanceof PageFragmentCallbacks)) {
            throw new ClassCastException("Activity must implement PageFragmentCallbacks");
        }

        mCallbacks = (PageFragmentCallbacks) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }  
    
}
